﻿using System.Security.Permissions;
using System.Web;
using System.Web.SessionState;
using EOS.Framework.Contracts.Web.Routing;
using log4net;

namespace EOS.Framework.Web.Mvc
{
    [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class DispatchHttpHandler : DispatchHandler, IRequiresSessionState
    {
        private MatchingRoute _currentRoute;
        private readonly ILog _logger = LogManager.GetLogger(typeof(DispatchHttpHandler));

        public DispatchHttpHandler(MatchingRoute currentRoute)
        {
            this._currentRoute = currentRoute;
        }

        protected MatchingRoute CurrentRoute
        {
            get { return _currentRoute; }
            set { _currentRoute = value; }
        }

        #region IHttpHandler Member

        public override void ProcessRequest(HttpContext context)
        {
            _logger.Debug("MVC request started");

            HttpSessionState session = context.Session;

            Utils.HighPerformanceTimer timer = new Utils.HighPerformanceTimer();
            timer.Start();

            IDispatcher dispatcher = Kernel.Unity.Current.Resolve<IDispatcher>();
            dispatcher.Dispatch(context, _currentRoute);

            timer.Stop();

            _logger.Debug("MVC request finished, duration: " + timer.Duration);
        }

        #endregion
    }
}
